package util;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class MyClassLoad extends ClassLoader {

    //等于项目的根目录下的webapps目录
    private String loadrootpath = "D:/lagou-homework/engineeringcode/Minicat/src/main/webapps";

    private String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
    public  MyClassLoad(){

    }
    public  MyClassLoad(String path){
        this.path = path;
    }

    //name为字节码文件的"位置+文件名"
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException  {

        String contextpath = loadrootpath + "/" + path + "/WEB-INF/classes/" + name;
        String cname = contextpath.replace(".", "/") + ".class";//获取字节码文件名

        try {
            byte[] bytes = null;
            bytes = Files.readAllBytes(Paths.get(cname));
            //技术入口，调用父类ClassLoader中的defineClass()方法生成c对象
            Class<?> c = this.defineClass(name, bytes, 0, bytes.length);
            return c;
        } catch (IOException e) {
            throw new ClassNotFoundException(name);
        }
    }

}
